<?php
/**
 * 商机控制器
 * @author 聂哥
 * @Date: 2023-01-17 12:11:21
*/

namespace app\crm\controller\business;

use app\admin\model\SystemAdmin;
use app\common\controller\CrmController;
use app\common\service\BaseService;
use app\crm\model\BaseCourse;
use app\crm\model\CrmBusiness;
use app\crm\model\CrmBusinessProduct;
use app\crm\model\CrmCustomer;
use app\crm\model\CrmRecord;
use app\crm\traits\Curd;
use think\Db;

class Index extends CrmController
{
    protected $validate = 'business\Business';
    protected $model = 'CrmBusiness';
	
	public function initialize()
    {
        parent::initialize();
        if( in_array($this->request->action(),['add','edit']) ){
            $this->assign('customerOwnerList', BaseService::getCustomerOwnerList());
            $this->assign('currentCourseList', BaseService::getCurrentCourseList());
        }
    }

    /**
     * @NodeAnotation(title="列表")
     */    
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $where[] =  ['owner_user_id', '<>', 0];
            $count = $this->model::with('customer,create_user,owner_user')
                ->where($where)
                ->count();
            $list = $this->model::with('customer,create_user,owner_user')
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * 添加商机
     * @MethodAuthor: 聂哥
     * @Date: 2023-01-17 15:01:19
     */
    public function add()
    {
         if ($this->request->isPost()) {
            $post = $this->request->post();
            $customer = CrmCustomer::get($post['customer_id']);
            if (!$customer){
                $this->error('没有找到客户');
            }
            
            $post['next_time'] = $post['next_time'] ? strtotime($post['next_time']) : 0;
            $post['deal_time'] = $post['deal_time'] ? strtotime($post['deal_time']) : 0;
            $post = array_merge($post, [
                'owner_user_id' => $customer['owner_user_id'],
                'type_id' => '1'
            ]);

            $validate = new $this->validate();
            if ($validate->check($post) == false) 
                return $this->error($validate->getError());
            Db::startTrans();
            try {
                $result = $this->model->allowField(true)->save($post);
                //添加商机产品
                $product_data = [];
                $pids = explode(',',$this->request->post("product_ids"));
                $business_id = $this->model->id;
                 foreach ($pids as $pid) {
                    $product = BaseCourse::get($pid);
                    $rows = ['course_id'=>$pid,'business_id'=>$business_id];
                    $rows['price'] = $product['price'];
                    $rows['product_sku'] = $product['sku'];
                    $rows['nums'] = 1;
                    $product_data[] = $rows;
                }
                $this->model->product()->saveAll($product_data);
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                $this->error($th->getMessage());
            }
            
            if( !$result ){
                return $this->error('保存失败');
            }
            return $this->success('保存成功');
        }
        $list= CrmCustomer::where('id',$this->request->param('id'))->field(['id'=>'value','name'])->select()->toArray();
        return $this->fetch('add',['data'=>$list]);
    }

    /**
     * 商机编辑
     * @MethodAuthor: 聂哥
     * @Date: 2023-01-17 18:52:26
     */
    public function edit($id)
    {
        $list = $this->model::with('customer')->where('id',$id)->find();
        return $this->fetch('edit',['data'=>$list]);
    }

    /**
     * 关联商品
     * @MethodAuthor: 聂哥
     * @Date: 2023-01-17 15:48:26
     */
    public function businessProduct()
    {
        list($page, $limit, $where) = $this->buildTableParames();

        $count = CrmBusinessProduct::with('info')
                ->where($where)
                ->count();
        $list = CrmBusinessProduct::with('info')
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
        $data = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }

    /**
     * 跟进
     */
    public function record()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return $this->error('缺少id参数');
        }
        if ($this->request->isAjax()) {
            list($page, $limit, $where) = $this->buildTableParames();
            $count = CrmRecord::with('createUser')->where('types_id',$id)->where($where)
                ->count();
            $list = CrmRecord::with('createUser')->where('types_id',$id)->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('business',CrmBusiness::get($id));
        $this->assign('record_methods',BaseService::getRecordMethodList());
        return $this->fetch();
    }
}
